package com.example.springsecrity;


import com.example.model.ResModel.AccountInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class  UserDetailsServiceImpl implements UserDetailsService {
//
//    @Autowired
//    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("loadUserByUsername");
//        //根据用户名查询用户信息
//        LambdaQueryWrapper<AccountInfo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(User::getUserName,username);
//        User user = userMapper.selectOne(wrapper);
//        //如果查询不到数据就通过抛出异常来给出提示
//        if(Objects.isNull(user)){
//            throw new RuntimeException("用户名或密码错误");
//        }
//        //TODO 根据用户查询权限信息 添加到LoginUser中


        //权限列表
        Collection<GrantedAuthority> grantedAuthorityCollection=new ArrayList<>();
        Collection<String> menus=new ArrayList<>();
        AccountInfo user = new AccountInfo();
        if(username.equals("admin")||username.equals("user"))
        {
            user.setLogonName(username);
            PasswordEncoder encode=new BCryptPasswordEncoder();
            String tt=encode.encode("123");

            List<String> authList=new ArrayList<>();
            if(username.equals("admin"))
            {
                menus.add("admin");
                authList.add("admin");
            }else if(username.equals("user")){
                menus.add("user");
                authList.add("user");
            }

            for(String temp:authList){
                SimpleGrantedAuthority grantedAuthority=new SimpleGrantedAuthority(temp);
                grantedAuthorityCollection.add(grantedAuthority);
            }
            ///123   $2a$10$DSZmLEtJnfEE/6sHlaGS5eLDz7dM8lw4GoPtYJmTfb/gqXn/J4oz2
            user.setPassword("{bcrypt}$2a$10$GMlgq7W9cnTPZyozX1mddeeLlvZZp9LIjSkpO8a4z.NVTzzMUUtPe");

        }else
        {
            log.info("用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }
        //封装成UserDetails对象返回
        LoginUser loginUser=new LoginUser();
        loginUser.setMenus(menus);
        loginUser.setUsername(user.getLogonName());
        loginUser.setPassword(user.getPassword());
        loginUser.setUser(user);

        return loginUser;

    }
}
